<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      /*
  二分查找的前提就是数组有序。
  难点在于二分查找的边界条件是 while(left<right)  ---right=nums.length-1  right=middle-1  [ ]
  还是while(left<right)  ---  right的边界条件==nums.length right=middle  [)
  */
      var search = function (nums, target) {
        //数组有序，用二分
        let left = 0;
        let right = nums.length;
        //因为right不能选中，必须从最后一位的下一位开始
        while (left < right) {
          let middle = parseInt((left + right) / 2);
          if (nums[middle] < target) {
            left = middle + 1;
          } else if (nums[middle] > target) {
            right = middle;
          } else {
            return middle;
          }
        }
      };
      console.log(search([-1, 0, 3, 5, 9, 12], 9));
    </script>
  </body>
</html>
